package com.wecan.micro.feign;

import cn.dev33.satoken.SaManager;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * @Author liuzhihao
 * @Date 2022.01.26
 * @Version ${version}
 * @Description ${description}
 */
public class FeignRequestInterceptor implements RequestInterceptor {


    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        /// 兼容应用内请求 1. 如内部应用访问另一个应用的接口
        if (requestAttributes == null) {
            return;
        }
        HttpServletRequest request = requestAttributes.getRequest();
        String tokenName = SaManager.getConfig().getTokenName();
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            String tokenValue = null;
            for (int i = 0; i < cookies.length; i++) {
                if (StringUtils.equals(cookies[i].getName(), tokenName)) {
                    tokenValue = cookies[i].getValue();
                    break;
                }
            }
            requestTemplate.header(tokenName, tokenValue);
        }
    }
}
